package com.mingda.weathermagiccenter.task;


import com.mingda.weathermagiccenter.dto.StationBean;
import com.mingda.weathermagiccenter.dto.StationFcBean;
import com.mingda.weathermagiccenter.dto.WeatherFcResultBean;
import com.mingda.weathermagiccenter.dto.WeatherResultBean;
import com.mingda.weathermagiccenter.pojo.WsStationData;
import com.mingda.weathermagiccenter.pojo.WsStationDataCur;
import com.mingda.weathermagiccenter.pojo.WsStationFcData;
import com.mingda.weathermagiccenter.pojo.WsStationFcDataCur;
import com.mingda.weathermagiccenter.service.WsStationDataCurService;
import com.mingda.weathermagiccenter.service.WsStationDataService;
import com.mingda.weathermagiccenter.service.WsStationFcDataCurService;
import com.mingda.weathermagiccenter.service.WsStationFcDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Async
@Slf4j
@Configuration // 1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling // 2.开启定时任务
@ConditionalOnProperty(prefix = "weatherapi",name = "enabled",havingValue = "true")
public class InsertQxjTask {


    @Autowired
    private WsStationFcDataService wsStationFcDataService;

    @Autowired
    private WsStationFcDataCurService wsStationFcDataCurService;
    @Autowired
    private WsStationDataService wsStationDataService;

    @Autowired
    private WsStationDataCurService wsStationDataCurService;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${weatherapi.regionstation.asyncurl:}")
    private String regionurl;
    @Value("${weatherapi.areastation.asyncurl:}")
    private String areaurl;

    @Value("${weatherapi.regionfc.asyncurl:}")
    private String regionfcurl;
    /**
     * 从远端API接口获得站点天气数据进行同步从头开始同步
     * 简单点 实时获取已小时为单位s
     */

    @Scheduled(cron = "${weatherapi.areastation.cron}")
    public void asyncstationweatherapi() {
        log.info("开始同步区域站天气数据");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 将时间四舍五入到整点
        LocalDateTime roundedTime = now.withMinute(0).withSecond(0).withNano(0);
        // 格式化时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String timeString = roundedTime.format(formatter);
        Map<String, String> param = new HashMap<String, String>();
        param.put("btime",timeString);
        param.put("etime",timeString);
        String requesturl = areaurl +  "?etime={etime}&btime={btime}";

        ResponseEntity<WeatherResultBean> res = restTemplate.getForEntity(requesturl, WeatherResultBean.class,param);
        List<WsStationData> list = new ArrayList<WsStationData>();
        List<WsStationDataCur> list2 = new ArrayList<WsStationDataCur>();
        for (StationBean point : res.getBody().data) {
            WsStationData ws = new WsStationData();
            ws.setStationkey(point.getStationKey());
            ws.setPres(point.getPres());
            ws.setHumi(point.getHumi());
            ws.setPrec(point.getPrec());
            ws.setSnow(point.getSnow());
            ws.setWepNow(point.getWep_now());
            ws.setWepTxt(point.getWEP_NowDescription());
            ws.setTemp(point.getTemp());
            ws.setHumiMin(point.getHumiMin());
            ws.setHumi(point.getHumi());
            ws.setPresSea(point.getPres_sea());
            ws.setTempMin(point.getTemp_min());
            ws.setTempMax(point.getTemp_max());
            ws.setWinInstDir(point.getWinInstDir());
            ws.setWinInstVel(point.getWinInstVel());
            LocalDateTime localDateTime = LocalDateTime.parse(point.getTimeBase(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
            ws.setTimebase(localDateTime);
            ws.setWin10Dir(point.getWin_10_dir());
            ws.setWin10Vel(point.getWin10Vel());
            String month = point.getTimeBase().replace("-","");
            month = month.substring(0,6);
            ws.setMonth(month);   //表分区月份 比填写
            list.add(ws);

            WsStationDataCur wsc = new WsStationDataCur();
            try {
                BeanUtils.copyProperties(wsc,ws);
                list2.add(wsc);
            } catch (Exception e) {

            }

        }
        log.info("更新同步区域站{}条"+ list.size());
        wsStationDataService.saveOrUpdateBatchById(list);
        wsStationDataCurService.saveOrUpdateBatchById(list2); //插入当前表



    }


    @Scheduled(cron = "${weatherapi.regionstation.cron}")
    public void asyncregionweatherapi() {
        log.info("开始同步国家站天气数据");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 将时间四舍五入到整点
        LocalDateTime roundedTime = now.withMinute(0).withSecond(0).withNano(0);
        // 格式化时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String timeString = roundedTime.format(formatter);
        Map<String, String> param = new HashMap<String, String>();
        param.put("btime",timeString);
        param.put("etime",timeString);
        String requesturl = regionurl +  "?etime={etime}&btime={btime}";

        ResponseEntity<WeatherResultBean> res = restTemplate.getForEntity(requesturl, WeatherResultBean.class,param);
        List<WsStationData> list = new ArrayList<WsStationData>();
        List<WsStationDataCur> list2 = new ArrayList<WsStationDataCur>();

        for (StationBean point : res.getBody().data) {
            WsStationData ws = new WsStationData();
            ws.setStationkey(point.getStationKey());
            ws.setPres(point.getPres());
            ws.setHumi(point.getHumi());
            ws.setPrec(point.getPrec());
            ws.setSnow(point.getSnow());
            ws.setWepNow(point.getWEP_Now());
            ws.setWepTxt(point.getWEP_NowDescription());
            ws.setTemp(point.getTemp());
            ws.setHumiMin(point.getHumiMin());
            ws.setHumi(point.getHumi());
            ws.setPresSea(point.getPres_sea());
            ws.setTempMin(point.getTemp_min());
            ws.setTempMax(point.getTemp_max());
            ws.setWinInstDir(point.getWinInstDir());
            ws.setWinInstVel(point.getWinInstVel());
            LocalDateTime localDateTime = LocalDateTime.parse(point.getTimeBase(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
            ws.setTimebase(localDateTime);
            ws.setWin10Dir(point.getWin_10_dir());
            ws.setWin10Vel(point.getWin10Vel());
            String month = point.getTimeBase().replace("-","");
            month = month.substring(0,6);
            ws.setMonth(month);   //表分区月份 比填写
            list.add(ws);


            WsStationDataCur wsc = new WsStationDataCur();
            try {
                BeanUtils.copyProperties(wsc,ws);
                list2.add(wsc);
            } catch (Exception e) {

            }



        }
        log.info("更新同步国家站{}条"+ list.size());
        wsStationDataService.saveOrUpdateBatchById(list);
        wsStationDataCurService.saveOrUpdateBatchById(list2); //插入当前表
    }


    /**
     * 同步天气预报数据
     */
    @Scheduled(cron = "${weatherapi.regionfc.cron}")
    public void asyncregionfcweathera() {
        log.info("开始同步国家站预报数据");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 将时间四舍五入到整点
        LocalDateTime roundedTime = now.withMinute(0).withSecond(0).withNano(0);
        // 格式化时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String timeString = roundedTime.format(formatter);
        Map<String, String> param = new HashMap<String, String>();
        param.put("btime",timeString);
        param.put("etime",timeString);
        String requesturl = regionfcurl +  "?etime={etime}&btime={btime}";

        ResponseEntity<WeatherFcResultBean> res = restTemplate.getForEntity(requesturl, WeatherFcResultBean.class,param);
        List<WsStationFcData> list = new ArrayList<WsStationFcData>();
        List<WsStationFcDataCur> list2 = new ArrayList<WsStationFcDataCur>();
        for (StationFcBean point : res.getBody().data) {
            WsStationFcData ws = new WsStationFcData();
            ws.setStationkey(point.getStationKey());
            ws.setPres(point.getPres());
            ws.setHumi(point.getHumi());
            ws.setPrec(point.getPrec());
            ws.setWep(point.getWep());
            ws.setTemp(point.getTemp());
            ws.setValidtime(point.getValidtime());
            ws.setValidtimeMax(point.getValidtime_max());
            ws.setHumi(point.getHumi());
            ws.setWinDir(point.getWin_dir());
            ws.setWinVel(point.getWin_vel());
            ws.setWepTxt(point.getWEP_NowDescription());


            LocalDateTime localDateTime = LocalDateTime.parse(point.getTimeBase(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
            ws.setTimebase(localDateTime);

            LocalDateTime fcDateTime = localDateTime.plus(point.getValidtime(), ChronoUnit.HOURS);
            ws.setFctime(fcDateTime);

            String month = point.getTimeBase().replace("-","");
            month = month.substring(0,6);
            ws.setMonth(month);   //表分区月份 比填写


            WsStationFcDataCur wsc = new WsStationFcDataCur();
            try {
                BeanUtils.copyProperties(wsc,ws);
                list2.add(wsc);
            } catch (Exception e) {

            }


            list.add(ws);
        }
        log.info("更新同步国家站{}条"+ list.size());
        wsStationFcDataService.saveOrUpdateBatchById(list);
        wsStationFcDataCurService.saveOrUpdateBatchById(list2); //插入当前表
    }





}
